package net.thxjj.mobileServer.service;


import com.amazonaws.services.iot.client.AWSIotException;
import com.amazonaws.services.iot.client.AWSIotMqttClient;
import lombok.extern.slf4j.Slf4j;
import net.thxjj.mobileServer.config.AwsIotAccountConfig;
import net.thxjj.mobileServer.entity.DataBean;
import net.thxjj.mobileServer.util.sampleUtil.SampleUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class AwsIotDeviceClientComponent implements ApplicationRunner {

    public AwsIotDeviceClientComponent(){
    }

    public static final String CLIENT_ID = "demo-server-202207";

    @Autowired
    private AWSIotMqttClient mqttClient;



    @Override
    public void run(ApplicationArguments args) throws Exception {
        mqttClient.connect();
        log.info("aws mqtt server 客户端连接成功");
    }

    @Bean(name = "awsIotMqttClient")
    public AWSIotMqttClient awsIotMqttClient() {
        log.info("创建 awsIotMqttClient bean");
        String clientEndpoint = SampleUtil.getConfig("clientEndpoint");
        String clientId = SampleUtil.getConfig("clientId");

        String certificateFile = SampleUtil.getConfig("certificateFile");
        String privateKeyFile = SampleUtil.getConfig("privateKeyFile");
        if (mqttClient == null && certificateFile != null && privateKeyFile != null) {
            String algorithm = SampleUtil.getConfig("keyAlgorithm");
            SampleUtil.KeyStorePasswordPair pair = SampleUtil.getKeyStorePasswordPair(certificateFile, privateKeyFile, algorithm);

            mqttClient = new AWSIotMqttClient(clientEndpoint, clientId, pair.keyStore, pair.keyPassword);
        }
        return mqttClient;
    }

    /**
     * 消息推送
     * @param topic
     * @param dataBean
     * @throws AWSIotException
     */
    public void pushMessage(String topic, DataBean dataBean) throws AWSIotException {
        log.info("server topic={},>>> {}", topic, dataBean.toString());
        mqttClient.publish(topic,dataBean.toString());
    }

}
